const state = {
  token: localStorage.getItem('token') || '',
  userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
  roles: JSON.parse(localStorage.getItem('roles') || '[]'),
  permissions: JSON.parse(localStorage.getItem('permissions') || '[]')
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  },
  SET_ROLES(state, roles) {
    state.roles = roles
    localStorage.setItem('roles', JSON.stringify(roles))
  },
  SET_PERMISSIONS(state, permissions) {
    state.permissions = permissions
    localStorage.setItem('permissions', JSON.stringify(permissions))
  },
  CLEAR_USER(state) {
    state.token = ''
    state.userInfo = {}
    state.roles = []
    state.permissions = []
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('roles')
    localStorage.removeItem('permissions')
  }
}

const actions = {
  login({ commit }, loginData) {
    commit('SET_TOKEN', loginData.token)
    commit('SET_USER_INFO', {
      userId: loginData.userId,
      username: loginData.username,
      nickname: loginData.nickname
    })
    commit('SET_ROLES', loginData.roles || [])
    commit('SET_PERMISSIONS', loginData.permissions || [])
  },
  logout({ commit }) {
    commit('CLEAR_USER')
  }
}

const getters = {
  token: state => state.token,
  userInfo: state => state.userInfo,
  roles: state => state.roles,
  permissions: state => state.permissions,
  hasPermission: state => permission => {
    return state.permissions.includes(permission)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
